<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多模态搜索项目技术文档</title>
    <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/github.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/index.css">
</head>

<body>
    <!-- 头部 -->
    <header>
        <div class="header-content">
            <h1 class="header-title">
                <i class="fas fa-search"></i>
                多模态搜索项目技术文档
            </h1>
            <div class="header-actions">
                <button class="theme-toggle" id="themeToggle" title="切换主题">
                    <i class="fas fa-moon"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 侧边栏切换按钮 -->
    <button class="sidebar-toggle" id="sidebarToggle">
        <i class="fas fa-bars"></i>
    </button>

    <!-- 侧边栏遮罩层 -->
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    <!-- 侧边栏 -->
    <aside class="sidebar" id="sidebar">
        <div class="search-container">
            <input type="text" class="search-input" id="searchInput" placeholder="搜索文档...">
            <i class="fas fa-search search-icon"></i>
        </div>

        <nav class="nav-section">
            <h3 class="nav-section-title">快速导航</h3>
            <ul class="nav-list" id="navList">
                <!-- 导航项将通过JavaScript动态生成 -->
            </ul>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <main class="main-container">
        <div class="content-wrapper">
            <div class="loading" id="loading">
                <div class="spinner"></div>
            </div>
            <article class="markdown-body" id="content" style="display: none;">
                <!-- Markdown内容将通过JavaScript加载并渲染 -->
            </article>
        </div>
    </main>

    <!-- 返回顶部按钮 -->
    <button class="back-to-top" id="backToTop">
        <i class="fas fa-arrow-up"></i>
    </button>

    <!-- 引入JavaScript库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/9.1.2/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/DOMPurify/3.0.5/purify.min.js"></script>

    <script>
        // 配置marked选项
        marked.setOptions({
            highlight: function (code, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    return hljs.highlight(code, { language: lang }).value;
                }
                return hljs.highlightAuto(code).value;
            },
            breaks: true,
            gfm: true
        });

        // 全局变量
        let markdownContent = '';
        let isDarkTheme = false;

        // DOM元素
        const loading = document.getElementById('loading');
        const content = document.getElementById('content');
        const navList = document.getElementById('navList');
        const searchInput = document.getElementById('searchInput');
        const themeToggle = document.getElementById('themeToggle');
        const sidebarToggle = document.getElementById('sidebarToggle');
        const sidebar = document.getElementById('sidebar');
        const backToTop = document.getElementById('backToTop');

        // 初始化
        document.addEventListener('DOMContentLoaded', function () {
            loadMarkdownContent();
            setupEventListeners();
            checkDarkTheme();
        });

        // 加载Markdown内容
        async function loadMarkdownContent() {
            try {
                // 检查必要的库是否已加载
                if (typeof marked === 'undefined') {
                    throw new Error('marked库未加载');
                }
                if (typeof hljs === 'undefined') {
                    throw new Error('highlight.js库未加载');
                }
                if (typeof DOMPurify === 'undefined') {
                    console.warn('DOMPurify库未加载，跳过内容净化');
                }

                const response = await fetch('多模态搜索项目技术文档.md');
                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }
                markdownContent = await response.text();

                // 渲染Markdown内容
                const htmlContent = marked.parse(markdownContent);
                content.innerHTML = typeof DOMPurify !== 'undefined' ?
                    DOMPurify.sanitize(htmlContent) : htmlContent;

                // 生成导航
                generateNavigation();

                // 显示内容，隐藏加载动画
                loading.style.display = 'none';
                content.style.display = 'block';

                // 高亮代码块
                if (typeof hljs !== 'undefined') {
                    hljs.highlightAll();
                }

                // 处理图片链接
                processImageLinks();

            } catch (error) {
                console.error('加载Markdown内容失败:', error);
                loading.innerHTML = `
                    <div style="text-align: center; color: #d73a49;">
                        <i class="fas fa-exclamation-triangle" style="font-size: 48px; margin-bottom: 20px;"></i>
                        <h3>加载文档失败</h3>
                        <p>错误信息: ${error.message}</p>
                        <p>请确保以下文件存在:</p>
                        <ul style="text-align: left; display: inline-block;">
                            <li>多模态搜索项目技术文档.md</li>
                        </ul>
                        <button onclick="location.reload()" style="margin-top: 15px; padding: 8px 16px; background-color: #0366d6; color: white; border: none; border-radius: 4px; cursor: pointer;">
                            重新加载
                        </button>
                    </div>
                `;
            }
        }

        // 生成导航
        function generateNavigation() {
            const headings = content.querySelectorAll('h1, h2, h3, h4, h5, h6');
            const navItems = [];

            headings.forEach((heading, index) => {
                // 为标题添加ID，便于跳转
                const id = `heading-${index}`;
                heading.id = id;

                // 创建导航项
                const level = parseInt(heading.tagName.substring(1));
                const navItem = {
                    id: id,
                    text: heading.textContent,
                    level: level
                };
                navItems.push(navItem);
            });

            // 渲染导航列表
            navList.innerHTML = navItems.map(item => `
                <li class="nav-item">
                    <a href="#${item.id}" class="nav-link" data-level="${item.level}">
                        ${'&nbsp;'.repeat((item.level - 1) * 2)}${item.text}
                    </a>
                </li>
            `).join('');
        }

        // 处理图片链接
        function processImageLinks() {
            const images = content.querySelectorAll('img');
            images.forEach(img => {
                // 如果是相对路径，转换为绝对路径
                if (img.src && !img.src.startsWith('http') && !img.src.startsWith('data:')) {
                    img.src = img.src;
                }

                // 添加点击放大功能
                img.style.cursor = 'pointer';
                img.addEventListener('click', function () {
                    window.open(this.src, '_blank');
                });
            });
        }

        // 设置事件监听器
        function setupEventListeners() {
            // 搜索功能
            searchInput.addEventListener('input', function () {
                const query = this.value.toLowerCase();
                filterContent(query);
            });

            // 主题切换
            themeToggle.addEventListener('click', toggleTheme);

            // 侧边栏切换
            sidebarToggle.addEventListener('click', function () {
                toggleSidebar();
            });

            // 点击遮罩层关闭侧边栏
            const sidebarOverlay = document.getElementById('sidebarOverlay');
            if (sidebarOverlay) {
                sidebarOverlay.addEventListener('click', function () {
                    closeSidebar();
                });
            }

            // 点击内容区域关闭侧边栏（移动端）
            content.addEventListener('click', function () {
                if (window.innerWidth <= 768) {
                    closeSidebar();
                }
            });
            
            // 处理窗口大小变化
            window.addEventListener('resize', function() {
                if (window.innerWidth > 768) {
                    closeSidebar();
                }
            });

            // 导航点击事件
            navList.addEventListener('click', function (e) {
                if (e.target.classList.contains('nav-link')) {
                    e.preventDefault();
                    const targetId = e.target.getAttribute('href').substring(1);
                    const targetElement = document.getElementById(targetId);

                    if (targetElement) {
                        // 平滑滚动到目标位置
                        targetElement.scrollIntoView({
                            behavior: 'smooth',
                            block: 'start'
                        });

                        // 更新活动状态
                        updateActiveNavigation(targetId);

                        // 移动端关闭侧边栏
                        if (window.innerWidth <= 768) {
                            closeSidebar();
                        }
                    }
                }
            });

            // 滚动事件
            window.addEventListener('scroll', function () {
                // 更新返回顶部按钮状态
                if (window.pageYOffset > 300) {
                    backToTop.classList.add('visible');
                } else {
                    backToTop.classList.remove('visible');
                }

                // 更新导航活动状态
                updateActiveNavigationOnScroll();
            });

            // 返回顶部
            backToTop.addEventListener('click', function () {
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            });
        }

        // 搜索过滤内容
        function filterContent(query) {
            if (!query) {
                // 如果搜索框为空，显示所有内容
                const allElements = content.querySelectorAll('*');
                allElements.forEach(el => {
                    el.style.display = '';
                });
                return;
            }

            // 隐藏所有内容
            const allElements = content.querySelectorAll('*');
            allElements.forEach(el => {
                el.style.display = 'none';
            });

            // 搜索并显示匹配的内容
            const textNodes = [];
            const walker = document.createTreeWalker(
                content,
                NodeFilter.SHOW_TEXT,
                null,
                false
            );

            let node;
            while (node = walker.nextNode()) {
                if (node.textContent.toLowerCase().includes(query)) {
                    textNodes.push(node);
                }
            }

            // 显示包含搜索词的元素及其父元素
            textNodes.forEach(node => {
                let parent = node.parentElement;
                while (parent && parent !== content) {
                    parent.style.display = '';
                    parent = parent.parentElement;
                }
            });
        }

        // 切换主题
        function toggleTheme() {
            isDarkTheme = !isDarkTheme;
            document.body.classList.toggle('dark-theme', isDarkTheme);

            // 更新图标
            const icon = themeToggle.querySelector('i');
            icon.className = isDarkTheme ? 'fas fa-sun' : 'fas fa-moon';

            // 保存主题设置
            localStorage.setItem('theme', isDarkTheme ? 'dark' : 'light');
        }

        // 检查暗色主题
        function checkDarkTheme() {
            const savedTheme = localStorage.getItem('theme');
            isDarkTheme = savedTheme === 'dark' ||
                (!savedTheme && window.matchMedia('(prefers-color-scheme: dark)').matches);

            document.body.classList.toggle('dark-theme', isDarkTheme);
            const icon = themeToggle.querySelector('i');
            icon.className = isDarkTheme ? 'fas fa-sun' : 'fas fa-moon';
        }

        // 更新导航活动状态
        function updateActiveNavigation(targetId) {
            const navLinks = navList.querySelectorAll('.nav-link');
            navLinks.forEach(link => {
                link.classList.remove('active');
                if (link.getAttribute('href') === `#${targetId}`) {
                    link.classList.add('active');
                }
            });
        }

        // 滚动时更新导航活动状态
        function updateActiveNavigationOnScroll() {
            const headings = content.querySelectorAll('h1, h2, h3, h4, h5, h6');
            const scrollPosition = window.pageYOffset + 100;

            let activeHeading = null;
            headings.forEach(heading => {
                const headingTop = heading.offsetTop;
                if (headingTop <= scrollPosition) {
                    activeHeading = heading;
                }
            });

            if (activeHeading) {
                updateActiveNavigation(activeHeading.id);
            }
        }
        
        // 切换侧边栏
        function toggleSidebar() {
            sidebar.classList.toggle('open');
            const sidebarOverlay = document.getElementById('sidebarOverlay');
            if (sidebarOverlay) {
                sidebarOverlay.classList.toggle('active');
            }
        }
        
        // 关闭侧边栏
        function closeSidebar() {
            sidebar.classList.remove('open');
            const sidebarOverlay = document.getElementById('sidebarOverlay');
            if (sidebarOverlay) {
                sidebarOverlay.classList.remove('active');
            }
        }
        
        // 添加触摸滑动支持
        let touchStartX = 0;
        let touchEndX = 0;
        
        document.addEventListener('touchstart', function(e) {
            touchStartX = e.changedTouches[0].screenX;
        }, false);
        
        document.addEventListener('touchend', function(e) {
            touchEndX = e.changedTouches[0].screenX;
            handleSwipe();
        }, false);
        
        function handleSwipe() {
            // 从左边缘向右滑动打开侧边栏
            if (touchEndX - touchStartX > 50 && touchStartX < 30) {
                openSidebar();
            }
            // 从右向左滑动关闭侧边栏
            else if (touchStartX - touchEndX > 50 && sidebar.classList.contains('open')) {
                closeSidebar();
            }
        }
        
        function openSidebar() {
            sidebar.classList.add('open');
            const sidebarOverlay = document.getElementById('sidebarOverlay');
            if (sidebarOverlay) {
                sidebarOverlay.classList.add('active');
            }
        }
    </script>
</body>

</html>